package com.maxjay.component.metadata.core.formatter;

import java.util.Date;

import com.maxjay.common.util.date.DateUtil;
import com.maxjay.component.metadata.model.EntityField;
import com.maxjay.component.metadata.model.Record;


/**
 * 日期字段格式化器，数据库类型为varchar或char型
 * 
 * @author zhaixm
 *
 */
public class DateFieldFormatter implements FieldFormatter {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1106948707526351031L;
	
	private String displayFormat;
	
	private String storeFormat;
	
	public DateFieldFormatter(String displayFormat, String storeFormat) {
		this.displayFormat = displayFormat;
		this.storeFormat = storeFormat;
	}
	
	@Override
	public String convertDisplayVal(EntityField entityField, Record record) {
		return DateUtil.getDateStr(record.getValue(entityField.getName()), displayFormat);
	}

	@Override
	public Object convertStoreVal(EntityField entityField, Record record) {
		Object rtnDate = null;
		switch (entityField.getFieldType()) {
		case CHAR:
			rtnDate = DateUtil.getDateStr(record.getValue(entityField.getName()), storeFormat);
			break;
		case DATE:
			Object originalVal = record.getValue(entityField.getName());
			if(originalVal instanceof String) {
				// 由于数据库字段为Date型则转换为java.sql.Date
				rtnDate = new java.sql.Date(DateUtil.changeStrToDate((String)originalVal).getTime());
			} else if (originalVal instanceof Date) {
				rtnDate = new java.sql.Date(((Date)originalVal).getTime());
			}
			break;
		default:
			break;
		}
		return rtnDate;
	}

	public String getDisplayFormat() {
		return displayFormat;
	}

	public void setDisplayFormat(String displayFormat) {
		this.displayFormat = displayFormat;
	}

	public String getStoreFormat() {
		return storeFormat;
	}

	public void setStoreFormat(String storeFormat) {
		this.storeFormat = storeFormat;
	}

	@Override
	public String getFormatterType() {
		return "DATE_FORMATTER";
	}

}